package com.ruoyi.log.manager.factory;

/**
 * @program: ruoyi
 * @description: 异步任务处理工厂
 * @author: Abner
 * @create: 2021-10-19 14:17
 */

import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.log.domain.SysVisitLog;
import com.ruoyi.log.domain.SysVisitTimeLog;
import com.ruoyi.log.service.ISysVisitLogService;
import com.ruoyi.log.service.ISysVisitTimeService;
import com.ruoyi.log.utils.KeysCollector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Map;
import java.util.TimerTask;

/**
 * 异步工厂（产生任务用）
 *
 * @author ruoyi
 */
public class AsyncLogFactory {

    private static final Logger log = LoggerFactory.getLogger("visit_log");

    /**
     * 记录访问api信息
     *
     * @param visitLog 访问日志信息
     * @return 任务task
     */
    public static TimerTask recordOper(final SysVisitLog visitLog)
    {
        return new TimerTask()
        {
            @Override
            public void run()
            {
                SpringUtils.getBean(ISysVisitLogService.class).insertVisitlog(visitLog);
            }
        };
    }

    /**
     * 记录访问时间
     *
     * @param visitTimeLog 访问日志信息
     * @return 任务task
     */
    public static TimerTask recordVisitTime(final SysVisitTimeLog visitTimeLog)
    {
        return new TimerTask()
        {
            @Override
            public void run()
            {
                SpringUtils.getBean(ISysVisitTimeService.class).insertVisitTimeLog(visitTimeLog);
            }
        };
    }

    public static TimerTask recordUserLogout(final String expiredKey) {
        return new TimerTask()
        {
            @Override
            public void run()
            {
                if (expiredKey.startsWith("app:")) {
                    Map<String, Long> appMap = KeysCollector.getKeysMap().get(expiredKey);
                    //用户访问数据写入数据库
                    redisToMySQL(appMap);
                    //删除
                    if (appMap != null) {
                        KeysCollector.removeKey(expiredKey);
                    }
                    //更新访问时间
                    String[] keys = expiredKey.split(":");
                    SysVisitTimeLog sysVisitTimeLog = SpringUtils.getBean(ISysVisitTimeService.class).getVisitTimeLogbyToken(keys[2]);
                    Date startDate = sysVisitTimeLog.getStartTime();
                    long starttime = startDate.getTime();
                    Date date = new Date();
                    sysVisitTimeLog.setLeaveTime(date);
                    long leavetime = date.getTime();
                    long timelong = leavetime - starttime;
                    sysVisitTimeLog.setTimeLong(timelong);
                    SpringUtils.getBean(ISysVisitTimeService.class).updateVisitTimeLog(sysVisitTimeLog);
                } else {
                    log.info("redis过期key值:" + expiredKey);
                }
            }

        };
    }

    public static void redisToMySQL( Map<String, Long> keys){
        if (!keys.isEmpty()){
            // 读取key
            for (String key : keys.keySet()) {
                String[] redisKeys = key.split(":");
                String id = redisKeys[0];
                Long appId= Long.valueOf(id);
                String url = redisKeys[1];
                String token_key = redisKeys[2];
                Long invokecount = Long.valueOf(String.valueOf(keys.get(key)));
                SpringUtils.getBean(ISysVisitLogService.class).updateInvokeCount(appId, url, token_key, invokecount);
            }
        }
    }
}
